package com.yami.shop.platform.task;

import cn.hutool.extra.mail.MailException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yami.shop.bean.model.BlockchainShop;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.util.DataWebService;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.nft.common.model.NftGasDeploy;
import com.yami.shop.nft.common.model.NftRechargeActivity;
import com.yami.shop.nft.common.service.NftGasDeployService;
import com.yami.shop.nft.common.service.NftRechargeActivityService;
import com.yami.shop.service.BlockchainShopService;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.user.common.model.UserGasLog;
import com.yami.shop.user.common.service.UserGasLogService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class GasRechargeTask {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    @Lazy
    private UserGasLogService userGasLogService;

    @Autowired
    private BlockchainShopService blockchainShopService;

    @Autowired
    private ShopConfig shopConfig;

    @Autowired
    private DataWebService dataWebService;
    @Autowired
    private ShopDetailService shopDetailService;
    /**
     * 同步gas充值定时任务
     */
    @XxlJob("syncGasRechargeTask")
    public void syncGasRechargeTask() {

        while (true) {
            // 一次查询10条数据处理。减轻IO压力
            List<UserGasLog> list = userGasLogService.list(new QueryWrapper<UserGasLog>().lambda().eq(UserGasLog::getType,7)
                    .eq(UserGasLog::getIsPayed, 1).eq(UserGasLog::getTabStatus, 0).orderByAsc(UserGasLog::getCreateTime).last("limit 10"));
            if (list == null || list.isEmpty()) {
                break;
            }

            for (UserGasLog log : list) {
                // gas 充值
                UserGasLog update = new UserGasLog();
                update.setTabStatus(1);
                boolean saveStatus = userGasLogService.update(update, Wrappers.lambdaUpdate(UserGasLog.class).
                        eq(UserGasLog::getGasLogId, log.getGasLogId()));
                if (saveStatus) {
                    String remark = String.format("gas充值记录%s:向%s系统-%s用户-%s链", log.getGasLogId(), log.getPateTab(), log.getToUserId(), log.getChainTab());
                    if (log.getGasNum() <= 0) {
                        logger.info(String.format("%s-充值%s，同步gas充值成功", remark, log.getGasNum()));
                        continue;
                    }
                    BlockchainShop blockchainShop = blockchainShopService.getOne(Wrappers.lambdaQuery(BlockchainShop.class)
                            .eq(BlockchainShop::getShopId, log.getUserId()).eq(BlockchainShop::getBlockchainCode,log.getChainTab())
                            .eq(BlockchainShop::getIsCoin,'1'));
                    if (null == blockchainShop) {
                        logger.info(String.format("%s-充值%s，同步gas充值失败：未获取到链授权账户", remark, log.getGasNum()));
                        continue;
                    }
                    ShopDetail shopDetailByShopId = shopDetailService.getShopDetailByShopId(Long.valueOf(log.getUserId()));
                    Map<String, String> stringObjectMap = new HashMap<>();
                    stringObjectMap.put("totalTimes", log.getGasNum().toString());
                    stringObjectMap.put("createTime",log.getCreateTime().toString());

                    String url = shopConfig.getApiGatewayUrl() + "/nft/outapi/nftUser/rechargeForRomate";
                    try {
                        JSONObject jsonObject = dataWebService.hutoolPostWebService(url, stringObjectMap,shopDetailByShopId.getApiUser(),shopDetailByShopId.getApiPassword());
                        remark = String.format(remark + "-充值%s，同步gas充值", log.getGasNum());
                        logger.info(String.format("%s成功", remark));
                        if (null == jsonObject || jsonObject.getInteger("code") != Constant.SUCCESS_CODE ) {
                           throw new MailException( jsonObject.getString("msg"));
                        }
                    }catch (Exception e){
                        logger.error(String.format("%s失败：%s", remark, e.getMessage()));
                        update.setTabStatus(2);
                        userGasLogService.update(update, Wrappers.lambdaUpdate(UserGasLog.class).eq(UserGasLog::getGasLogId, log.getGasLogId()));
                    }
                }
            }
        }

    }
}
